import { request } from '../request';

// 导入后端实体类型
interface BackendApiDefinition {
  id: number;
  name: string;
  bizCode: string;
  description?: string;
  flowDefinition?: string;
  replyQueueTopic?: string;
  tenantId?: string;
  enabled: boolean;
  createTime?: string;
  updateTime?: string;
}

/** 计算引擎API */

// 接口定义相关API
/** 获取所有接口定义列表 */
export async function fetchApiDefinitions() {
  const response = await request<BackendApiDefinition[]>({
    url: '/api/compute/api-definitions',
    method: 'get'
  });

  // createFlatRequest 返回 { data, error, response } 格式
  if (response.error) {
    throw response.error;
  }

  // transformBackendResponse 已经提取了 data 字段，response.data 就是 BackendApiDefinition[]
  if (response.data && Array.isArray(response.data)) {
    return response.data.map(
      (item: BackendApiDefinition): Api.Compute.ApiDefinition => ({
        ...item,
        id: String(item.id), // 确保id是字符串类型
        status: item.enabled ? 'enabled' : 'disabled' // 将enabled布尔值映射为status字符串
      })
    );
  }

  return [];
}

/**
 * 获取指定ID的接口定义
 *
 * @param id 接口定义ID
 */
export async function fetchApiDefinitionById(id: string) {
  // 确保id是数字类型
  const numericId = Number(id);

  const response = await request<BackendApiDefinition>({
    url: `/api/compute/api-definitions/${numericId}`,
    method: 'get'
  });

  // createFlatRequest 返回 { data, error, response } 格式
  if (response.error) {
    throw response.error;
  }

  // transformBackendResponse 已经提取了 data 字段，response.data 就是 BackendApiDefinition
  if (response.data) {
    return {
      ...response.data,
      id: String(response.data.id), // 确保id是字符串类型
      status: response.data.enabled ? 'enabled' : 'disabled' // 将enabled布尔值映射为status字符串
    } as Api.Compute.ApiDefinition;
  }

  return null;
}

/**
 * 保存接口定义
 *
 * @param apiDefinition 接口定义对象
 */
export async function saveApiDefinition(apiDefinition: Api.Compute.ApiDefinition) {
  const { id, ...rest } = apiDefinition;
  const isUpdate = Boolean(id);

  // 将前端的status字段映射回后端的enabled字段
  const { status, ...otherFields } = rest;
  const payload = {
    ...otherFields,
    enabled: status === 'enabled', // 将status字符串映射为enabled布尔值
    id: isUpdate ? Number(id) : undefined // 确保id是数字类型
  };

  const response = await request<string>({
    url: '/api/compute/api-definitions',
    method: isUpdate ? 'put' : 'post',
    data: payload
  });

  // request函数已经通过transformBackendResponse自动提取了data字段
  return { data: response.data };
}

/**
 * 删除接口定义
 *
 * @param id 接口定义ID
 */
export async function deleteApiDefinition(id: string) {
  // 确保id是数字类型
  const numericId = Number(id);

  const response = await request<string>({
    url: `/api/compute/api-definitions/${numericId}`,
    method: 'delete'
  });

  // request函数已经通过transformBackendResponse自动提取了data字段
  return { data: response.data };
}

// 流程执行相关API
/**
 * 执行计算流程
 *
 * @param computeRequest 计算请求对象
 */
export function executeComputeFlow(computeRequest: Api.Compute.ComputeRequest) {
  return request<Api.Compute.ComputeResponse>({
    url: '/api/compute/execute',
    method: 'post',
    data: computeRequest
  });
}

/**
 * 验证计算流程
 *
 * @param flowDefinition 流程定义对象
 */
export function validateComputeFlow(flowDefinition: Api.Compute.FlowDefinition) {
  return request<{ valid: boolean; errors?: string[] }>({
    url: '/api/compute/validate',
    method: 'post',
    data: flowDefinition
  });
}

/**
 * 调试计算流程中的单个步骤
 *
 * @param step 步骤定义
 * @param input 输入数据
 */
export function debugComputeStep(step: Api.Compute.Step, input: any) {
  return request<any>({
    url: '/api/compute/debug-step',
    method: 'post',
    data: {
      step,
      input
    }
  });
}

/**
 * 逐步执行计算流程
 *
 * @param stepByStepRequest 逐步执行请求对象
 */
export function executeStepByStep(stepByStepRequest: Api.Compute.StepByStepRequest) {
  return request<Api.Compute.StepByStepResponse>({
    url: '/api/compute/step-by-step',
    method: 'post',
    data: stepByStepRequest
  });
}

/**
 * 继续执行下一步
 *
 * @param continueStepRequest 继续执行请求对象
 */
export function continueStep(continueStepRequest: Api.Compute.ContinueStepRequest) {
  return request<Api.Compute.StepByStepResponse>({
    url: '/api/compute/continue-step',
    method: 'post',
    data: continueStepRequest
  });
}
